package com.example.base.websocket.plugin;

import com.example.base.app.AppClassService;
import com.example.base.system.SysAppService;
import com.example.base.utils.ReflectUtils;
import com.example.base.websocket.AppWebSocket;
import com.example.base.websocket.interceptor.WebSockerMethodInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class AppWebSocketPlugin {

    @Autowired
    private ThreadPoolTaskExecutor asyncServiceExecutor;

    @Autowired
    private SysAppService sysAppService;

    @Autowired
    private AppClassService appClassService;

    @Autowired
    private AppWebSocketMap appWebSocketMap;

    public void loadAppWebSocketPlugin(String appName){
        asyncServiceExecutor.execute(()-> {
            log.info("开始加载应用name {} websocket 插件: ", appName);
            List<Class<?>> classList=appClassService.getClassByAppName(appName);
            if(classList!=null && classList.size() > 0){
                classList.forEach(e->{
                    Boolean isPlugin=ReflectUtils.isSubClass(e, AppWebSocket.class);
                    if(isPlugin){
                        log.info("websocket class {}",e.getName());
                        Enhancer enhancer = new Enhancer();
                        enhancer.setSuperclass(e);
                        enhancer.setCallback(new WebSockerMethodInterceptor(appName));
                        AppWebSocket userServiceProxy = (AppWebSocket) enhancer.create();
                        appWebSocketMap.addAppWebSocket(appName,userServiceProxy);
                        userServiceProxy.initExecute();
                    }
                });
            }
        });
    }


}
